<template>
  <div class="product-add-page">
    <van-nav-bar
      title="添加商品"
      left-arrow
      @click-left="router.back()"
    />

    <van-form @submit="onSubmit">
      <!-- 商品名称 -->
      <van-field
        v-model="productForm.productName"
        name="productName"
        label="商品名称"
        placeholder="请输入商品名称"
        :rules="[{ required: true, message: '请填写商品名称' }]"
      />

      <!-- 商品价格 -->
      <van-field
        v-model="productForm.price"
        name="price"
        label="商品价格"
        placeholder="请输入商品价格"
        :rules="[
          { required: true, message: '请填写商品价格' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的价格格式' }
        ]"
      >
        <template #button>
          <span class="price-unit">元</span>
        </template>
      </van-field>

      <!-- 商品描述 -->
      <van-field
        v-model="productForm.description"
        name="description"
        label="商品描述"
        placeholder="请输入商品描述"
        type="textarea"
        rows="2"
        autosize
      />

      <!-- 商品图片 -->
      <div class="image-upload">
        <div class="upload-label">商品图片</div>
        <van-uploader
          v-model="imageList"
          :max-count="1"
          :max-size="5 * 1024 * 1024"
          :after-read="afterRead"
          :before-read="beforeRead"
          accept="image/*"
          :preview-options="{
            closeable: true,
            showIndex: false
          }"
          :preview-image="true"
          :preview-full-image="true"
          :deletable="true"
          @delete="onDelete"
          @oversize="onOversize"
        >
          <template #default>
            <div class="upload-area" v-if="imageList.length === 0">
              <van-icon name="plus" size="24" />
              <div class="upload-text">上传图片</div>
            </div>
          </template>
        </van-uploader>
        <div class="upload-tips">
          <p>图片大小不超过5MB，格式为jpg或png</p>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-button">
        <van-button 
          round 
          block 
          type="primary" 
          native-type="submit"
          :loading="isSubmitting"
          :disabled="isSubmitting"
        >
          保存
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { addProduct, type Product } from '../api/product'

const router = useRouter()
const route = useRoute()

// 是否提交中
const isSubmitting = ref(false)
// 是否上传中
const uploading = ref(false)

// 商品表单数据
const productForm = ref({
  productName: '',
  price: '',
  description: '',
  categoryId: '',
  photo: '',
  photoBase64: ''
})

// 图片列表
const imageList = ref<any[]>([])

// 预检查图片
const beforeRead = (file: File | File[]) => {
  const files = Array.isArray(file) ? file : [file]
  
  // 检查文件类型
  const isImage = files.every(item => 
    item.type === 'image/jpeg' || 
    item.type === 'image/png'
  )
  
  if (!isImage) {
    showToast('请上传 jpg 或 png 格式图片')
    return false
  }
  
  return true
}

// 文件大小超出限制
const onOversize = () => {
  showToast('文件大小不能超过5MB')
}

// 图片上传处理
const afterRead = (items: any) => {
  const files = Array.isArray(items) ? items : [items]
  const file = files[0]?.file
  if (!file) return
  
  uploading.value = true
  
  const reader = new FileReader()
  reader.onload = (e) => {
    const result = e.target?.result as string
    // 设置图片的base64编码
    productForm.value.photoBase64 = result
    imageList.value = [{
      url: result,
      file,
      isImage: true
    }]
    uploading.value = false
  }
  reader.readAsDataURL(file)
}

// 删除图片
const onDelete = () => {
  imageList.value = []
  productForm.value.photoBase64 = ''
}

// 提交表单
const onSubmit = async () => {
  if (isSubmitting.value) return
  isSubmitting.value = true
  
  try {
    // 获取分类ID
    const categoryId = route.query.categoryId
    if (!categoryId) {
      showToast('缺少分类信息')
      return
    }
    
    // 创建新商品数据
    const newProduct: Omit<Product, 'id'> = {
      productName: productForm.value.productName,
      price: Number(productForm.value.price),
      description: productForm.value.description || '',
      categoryId: categoryId as string
    }
    
    // 调用API添加商品
    const success = await addProduct(
      newProduct, 
      imageList.value.length > 0 ? imageList.value[0].file : undefined
    )
    
    if (success) {
      showToast({
        type: 'success',
        message: '添加成功',
        position: 'bottom'
      })
      
      // 返回商品列表页
      router.back()
    }
  } catch (error) {
    console.error('添加商品失败:', error)
    showToast({
      type: 'fail',
      message: '添加商品失败',
      position: 'bottom'
    })
  } finally {
    isSubmitting.value = false
  }
}

onMounted(() => {
  // 初始化分类ID
  const categoryId = route.query.categoryId
  if (categoryId) {
    productForm.value.categoryId = categoryId as string
  }
})
</script>

<style lang="scss" scoped>
.product-add-page {
  min-height: 100vh;
  background: #f7f8fa;

  .price-unit {
    color: #969799;
    font-size: 14px;
  }

  .image-upload {
    padding: 16px;
    background: #fff;
    margin-top: 12px;

    .upload-label {
      margin-bottom: 8px;
      color: #323233;
    }
    
    .upload-tips {
      margin-top: 8px;
      color: #969799;
      font-size: 12px;
    }
    
    .upload-area {
      width: 100px;
      height: 100px;
      background: #f7f8fa;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #969799;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f2f3f5;
      }

      .upload-text {
        margin-top: 8px;
        font-size: 12px;
      }
    }
    
    .preview-cover {
      position: relative;
      width: 100%;
      height: 100%;
      
      .preview-cover-loading {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.4);
        display: flex;
        justify-content: center;
        align-items: center;
        
        .van-loading {
          color: #fff;
        }
      }
    }
    
    .delete-icon {
      position: absolute;
      right: -6px;
      top: -6px;
      color: #fff;
      font-size: 14px;
      background: rgba(0, 0, 0, 0.5);
      border-radius: 50%;
      padding: 2px;
    }
  }

  .submit-button {
    padding: 16px;
    margin-top: 24px;
  }
}
</style> 